const { v4 } = require("uuid");
const { Result } = require("@/libs/result");
const arrayUtil = require("@/utils/array.util");
const dateUtil = require("@/utils/date.util");
const dbTableNameConstant = require("@/constants/db-table-name.constant");
const CommonService = require("@/common/common.service");
const orderModel = require("./order.model");
const fileBusinessService = require("@/common/file-business.service");
const messageBusinessService = require("../../common/services/message-business.service");
const { TenantContext } = require("@/core/tenant-context");
const { BillingCalculatorService } = require("./billing-calculator.service");
const { TableStatusEnum, OrderStatusEnum } = require("./order.enum");

/**
 * 订单服务
 * @author Haor
 * @created_at 2025-06-05
 */
class OrderService {
	commonService = new CommonService();
	/**
	 * 创建桌台订单
	 * @param {*} data
	 */
	async createTableOrder(data) {
		try {
			const { table_id, table_rule_id } = data;

			// 查询桌台
			const [_tError, _td] = await orderModel.getTableById(table_id);
			if (_tError || !_td) {
				console.log("未查询到桌台规则");
				return Result.Failed("未查询到桌台");
			}

			// 判断桌台状态
			if (_td.status !== TableStatusEnum.Idle) {
				return Result.Failed("当前桌台不可使用");
			}

			// 查询规则
			const ruleResults = await orderModel.getGameTableRuleList({ table_id: table_id });
			if (ruleResults.code !== 200) {
				return Result.Failed("桌台订单创建失败");
			}

			// 当前所选择的规则
			const billingRule = ruleResults.results.find(rule => rule.id === table_rule_id);

			// 规则信息
			if (!billingRule) {
				console.log("未查询到桌台规则");
				return Result.Failed("桌台订单创建失败");
			}

			// 创建桌台订单
			const [_oError, order] = await orderModel.createTableOrder({
				order_type: 1,
				order_no: this.generateTableOrderNo(),
				table_id: table_id,
				start_time: dateUtil.formatDate(Date.now(), "yyyy-MM-dd HH:mm:ss"),
                player_count: data.player_count,
                applied_rule_id: table_rule_id,
                applied_rule_json: JSON.stringify(billingRule),
                total_amount: 0,
                actual_amount: 0,
				status: 0
			});
			if (_oError) {
				console.log("创建订单失败：", error);
				return Result.Failed("桌台订单创建失败");
			}

			// 更改桌台的状态为使用中
			const [_sError] = await orderModel.updateTableStatus(table_id, {
                status: TableStatusEnum.InUse,
                current_order_id: order.id
			});
			if (_sError) {
				console.log("创建订单失败：", _sError);
				return Result.Failed("桌台订单创建失败");
			}

			// 创建订单费用规则
			const [_bError] = await orderModel.createTableOrderBillingRule({
				order_id: order.id,
				rule_id: billingRule.id,
				rule_snapshot: JSON.stringify(billingRule)
			});
			if (_bError) {
				console.log("创建订单失败：", _bError);
				return Result.Failed("桌台订单创建失败");
			}

			// 返回结果
			return Result.Success(order);
		} catch (error) {
			console.log("桌台订单创建失败:", error);
			return Result.Failed("桌台订单创建失败");
		}
	}

	/**
	 * 创建订单商品
	 * @param {*} order_id
	 * @param {*} data
	 */
	async createTableOrderProduct({ order_id }, data) {
		try {
			const [_oError, _oData] = await orderModel.getOrderById(order_id);
			if (_oError) {
				console.log("桌台添加商品失败:", error);
				return Result.Success(`订单不存在`);
			}
            // 状态
            if (_oData.status !== OrderStatusEnum.UnderWay) {
                return Result.Success(`非进行中订单，无法添加商品`);
            }
            const { products } = data;

			// 1.商品数量map
			const productQuantityMap = products.reduce((pre, cur) => {
				pre[cur.id] = cur.quantity;
				return pre;
			}, {});

            // 通过传递过来的值获取商品信息
			const [_queryErr, _d] = await orderModel.queryProductList(products.map(i => i.id));
			if (_queryErr) {
				return Result.Failed("订单创建失败");
			}

			// 如果查询出来与传递的数量不一致
			if (products.length !== _d.length) {
				return Result.Failed("商品参数有误");
			}

			// 创建订单下的商品
			const orderProducts = _d.map(product => {
				return {
					order_id: order_id,
					item_type: 2,
					product_id: product.id,
					item_name: product.name,
					// 数量
					quantity: productQuantityMap[product.id],
					// 单价
					unit_price: product.price,
					// 总价
					total_price: product.price * productQuantityMap[product.id] || 0
				};
			});
			const [_pError] = await orderModel.createTableOrderProducts(orderProducts);
			if (_pError) {
				console.log(_pError);
				return Result.Failed("商品添加失败");
			}

			// 返回结果
			return Result.Success(_oData);
		} catch (error) {
			console.log("桌台添加商品失败:", error);
			return Result.Failed("桌台添加商品失败");
		}
	}

	/**
	 * 结算桌台订单
	 * @param {*} order_id
	 * @param {*} data
	 */
	async paymentTableOrder({ order_id }, data = {}) {
        try {
            // 查询订单信息
            const [_oError, _oData] = await orderModel.getOrderById(order_id);
            if (_oError) {
                return Result.Success(`订单不存在`);
            }
            // 状态
            if (_oData.status !== OrderStatusEnum.UnderWay) {
                return Result.Success(`非进行中的订单，无法结算`);
            }

            // 查询订单的桌台信息
            const [_tError, _tData] = await orderModel.getTableById(_oData.table_id);
            if (_tError) {
                console.log("桌台订单结算失败:", _tError);
                return Result.Failed("桌台订单结算失败");
            }

            // 获取订单下的规则
            const orderBillingRule = await orderModel.getOrderBillingRule(order_id);
            if (orderBillingRule.code !== 200) {
                console.log("订单规则获取失败");
                return Result.Failed("桌台订单结算失败");
            }
            if (orderBillingRule.results.length < 0) {
                console.log("订单规则获取失败");
                return Result.Failed("桌台订单结算失败");
            }

            // 查询订单下的所有商品
            const products = await orderModel.queryOrderProductList(order_id);
            if (products.code !== 200) {
                console.log("桌台订单结算失败:", error);
                return Result.Failed("桌台订单结算失败");
            }

            // 商品的总价
            const productTotalPrice = products.results.reduce((total, cur) => {
                total = total + cur.total_price;
                return total;
            }, 0);

            // 订单结束时间
            const ORDER_FINISH_DATE = dateUtil.formatDate(Date.now(), 'yyyy-MM-dd HH:mm:ss');
            // 获取桌台规则费用
            const tableTotalPrice = BillingCalculatorService.calculatorByRule(orderBillingRule.results[0], _oData.start_time, ORDER_FINISH_DATE);
            // 总价
            const orderTotalPrice = tableTotalPrice + productTotalPrice;

            // 修改订单状态、支付状态、支付类型
            const updateStatusResult = await this._updateOrderPaymentStatus({
                orderId: order_id,
                payStatus: OrderStatusEnum.PaymentMade,
                payType: 1,
                total_amount: orderTotalPrice || 0,
                discount_amount: data.discount_amount || 0
            });
            if (!updateStatusResult) {
                return Result.Failed("桌台订单结算失败");
            }

            // 修改桌台状态为空闲
			const [_sError] = await orderModel.updateTableStatus(_oData.table_id, {
                status: TableStatusEnum.Idle,
                current_order_id: null
			});
            if (_sError) {
                return Result.Failed("桌台订单结算失败");
            }

			// 返回结果
			return Result.Success(orderTotalPrice);
		} catch (error) {
			console.log("桌台订单结算失败:", error);
			return Result.Failed("桌台订单结算失败");
		}
    }
    
    /**
     * 修改订单支付状态
     * @param {*} param0 
     * @returns 
     */
    async _updateOrderPaymentStatus({ orderId, payStatus, payType, total_amount, discount_amount}) {
        try {
            const [error] = await orderModel.updateOrderStatus(orderId, {
                status: payStatus,
                payment_method: payType,
                total_amount: total_amount || 0,
                actual_amount: total_amount - discount_amount,
                discount_amount: discount_amount,
                operator: TenantContext.getCurrentUser() || ''
            });
            return !error;
        } catch (error) {
            console.log('修改订单支付状态异常：', error);
            return false;
        }
    }

    /**
     * 修改状态状态失败
     * @param {*} tableId 
     * @param {*} status 
     * @returns 
     */
    async _updateTableStatus(tableId, status) {
        try {
            const [error] = await orderModel.updateTableStatus(tableId, {
                status: status
            });
            return !error;
        } catch (error) {
            console.log('修改桌台状态失败：', error);
            return false;
        }
    }
    

	/**
	 * 创建零售订单
	 * @param {*} data
	 * @returns
	 */
	async createRetailOrder(data) {
		try {
			const { products } = data;
			// 1.商品数量map
			const productQuantityMap = products.reduce((pre, cur) => {
				pre[cur.id] = cur.quantity;
				return pre;
			}, {});
			// 通过传递过来的值获取商品信息
			const [_queryErr, _d] = await orderModel.queryProductList(products.map(i => i.id));
			if (_queryErr) {
				return Result.Failed("订单创建失败");
			}
			// 如果查询出来与传递的数量不一致
			if (products.length !== _d.length) {
				return Result.Failed("商品参数有误");
			}

            const total_amount = this.getOrderProductTotalPrice(_d, productQuantityMap) || 0;

			// 创建订单
			const [error, result] = await orderModel.createRetailOrder({
				// 订单编号
				order_no: this.generateRetailOrderNo(),
				// 订单类型
				order_type: 2,
				// 客户姓名
				customer_name: data.customer_name || "零售客户",
				// 客户手机号
				customer_phone: data.customer_phone || "",
				// 优惠金额
				discount_amount: data.discount_amount || 0,
				// 总金额
                total_amount: this.getOrderProductTotalPrice(_d, productQuantityMap) || 0,
                // 实收金额
                actual_amount: total_amount > 0 ? total_amount - (data.discount_amount || 0) : 0,
				// 状态
				status: 0,
				// 支付方式
				payment_method: data.payment_method || 1,
				// 操作员
				operator: TenantContext.getCurrentUser(),
				// 备注
				remark: data.remark || ""
			});
			if (error) {
				console.log(error);
				return Result.Failed("订单创建失败");
			}

			// 创建订单下的商品
			const orderProducts = _d.map(product => {
				return {
					order_id: result.id,
					item_type: 2,
					product_id: product.id,
					item_name: product.name,
					// 数量
					quantity: productQuantityMap[product.id],
					// 单价
					unit_price: product.price,
					// 总价
					total_price: product.price * productQuantityMap[product.id] || 0
				};
			});
			const [productError] = await orderModel.createRetailOrderProducts(orderProducts);
			if (productError) {
				console.log(error);
				return Result.Failed("订单创建失败");
			}
			return Result.Success(result);
		} catch (error) {
            console.log(error);
			return Result.Failed("订单创建失败");
		}
	}

	/**
	 * 获取订单商品的总价
	 * @param {*} productList
	 * @param {*} quantityMap
	 * @returns
	 */
	getOrderProductTotalPrice(productList, quantityMap) {
		let total = 0;
		productList.forEach(product => {
			total += product.selling_price * quantityMap[product.id];
		});
		return total;
	}

	/**
	 * 生成零售订单编号
	 * @returns
	 */
	generateRetailOrderNo() {
		const date = dateUtil.formatDate(Date.now(), "yyyyMMddHHmm");
		const random = Math.floor(Math.random() * 1000)
			.toString()
			.padStart(2, "0");
		return `R${date}${random}`;
	}

	/**
	 * 生成桌台订单编号
	 * @returns
	 */
	generateTableOrderNo() {
		const date = dateUtil.formatDate(Date.now(), "yyyyMMddHHmm");
		const random = Math.floor(Math.random() * 1000)
			.toString()
			.padStart(2, "0");
		return `T${date}${random}`;
	}
}

module.exports = {
	orderService: new OrderService()
};
